<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2018/5/17
 * Time: 下午8:24
 */
namespace Core\traits;

use Core\common\Assist;

trait Wechat
{
    public static $wxApiBaseUrl = 'https://api.weixin.qq.com';

    /**
     * 微信网页授权跳转
     * @param $appId
     * @param $backUrl
     * @param string $scope
     * @param string $state
     */
    public static function authRedirect($appId,$backUrl,$scope = 'userinfo',$state = '')
    {
        if($scope === 'base'){
            $scope = 'snsapi_base';
        }else{
            $scope = 'snsapi_userinfo';
        }
        if(empty($state)){
            $state = random(6);
        }

        $authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?%s#wechat_redirect';
        $baseUrl = sprintf($authUrl,http_build_query([
            'appid' => $appId,
            'redirect_uri' => $backUrl,
            'response_type' => 'code',
            'scope' => $scope,
            'state' => $state
        ]));
        header('Location:'.$baseUrl);
        exit();
    }

    /**
     * 微信code换用用户信息
     * @param $appId
     * @param $appSecret
     * @param $code
     * @return mixed
     */
    public static function oauth2UserInfo($appId,$appSecret,$code)
    {
        try{
            $url = sprintf('%s/sns/oauth2/access_token?%s',self::$wxApiBaseUrl,http_build_query([
                'appid' => $appId,
                'secret' => $appSecret,
                'code'   => $code,
                'grant_type' => 'authorization_code'
            ]));
            $result = ihttp_get($url);
            $content = json_decode($result['content'],true);
            if(isset($content['errcode'])){
                throw new \Exception($content['errmsg'],$content['errcode']);
            }
            if($content['scope'] === 'snsapi_base'){
                return $content;
            }
            $userInfo = self::_userInfo($content['access_token'],$content['openid']);
            return $userInfo;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }

    /**
     * 换取用户信息
     * @param $accessToken
     * @param $openId
     * @return mixed
     */
    private static function _userInfo($accessToken,$openId)
    {
        try{
            $url = sprintf('%s/sns/userinfo?%s',self::$wxApiBaseUrl,http_build_query([
                'access_token' => $accessToken,
                'openid' => $openId,
                'lang' => 'zh_CN'
            ]));
            $result = ihttp_get($url);
            $content = json_decode($result['content'],true);
            if(isset($content['errcode'])){
                throw new \Exception($content['errmsg'],$content['errcode']);
            }
            return $content;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }

    /**
     * 根据openid获取微信用户信息
     * @param $openid
     * @return mixed
     */
    public static function getUserInfoByOpenid($openid)
    {
        try{
            $accessToken = \Core\common\Wechat::assessToken();
            $url = sprintf('%s/cgi-bin/user/info?%s',self::$wxApiBaseUrl,http_build_query([
                'access_token' => $accessToken,
                'openid' => $openid,
                'lang' => 'zh_CN'
            ]));
            $result = ihttp_get($url);
            $content = json_decode($result['content'],true);
            if(isset($content['errcode'])){
                throw new \Exception($content['errmsg'],$content['errcode']);
            }
            return $content;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }
}